from rest_framework import serializers


class NestedModelSerializer(serializers.ModelSerializer):

    def create_nested_objects(self, instance, nested_data):
        """辅助方法：递归创建嵌套对象."""
        for attr, value in nested_data.items():
            nested_serializer_class = getattr(self.Meta, 'nested_serializers', {}).get(attr)

            if nested_serializer_class:
                nested_serializer = nested_serializer_class(data=value)
                if nested_serializer.is_valid():
                    nested_instance = nested_serializer.save()
                    setattr(instance, attr, nested_instance)
        instance.save()

    def update_nested_objects(self, instance, nested_data):
        """辅助方法：递归更新嵌套对象."""
        for attr, value in nested_data.items():
            nested_instance = getattr(instance, attr, None)
            nested_serializer_class = getattr(self.Meta, 'nested_serializers', {}).get(attr)

            if nested_instance and nested_serializer_class:
                nested_serializer = nested_serializer_class(instance=nested_instance, data=value, partial=True)
                if nested_serializer.is_valid():
                    nested_serializer.save()
            elif nested_serializer_class:
                # 如果嵌套实例不存在，则创建新的
                nested_serializer = nested_serializer_class(data=value)
                if nested_serializer.is_valid():
                    nested_instance = nested_serializer.save()
                    setattr(instance, attr, nested_instance)
        instance.save()

    def create(self, validated_data):
        """重写创建方法以处理嵌套数据."""
        nested_data = {}
        for attr in getattr(self.Meta, 'nested_serializers', {}).keys():
            nested_data[attr] = validated_data.pop(attr, None)

        instance = self.Meta.model.objects.create(**validated_data)
        self.create_nested_objects(instance, nested_data)
        return instance

    def update(self, instance, validated_data):
        """重写更新方法以处理嵌套数据."""
        nested_data = {}
        for attr in getattr(self.Meta, 'nested_serializers', {}).keys():
            nested_data[attr] = validated_data.pop(attr, None)

        for attr, value in validated_data.items():
            setattr(instance, attr, value)
        instance.save()

        self.update_nested_objects(instance, nested_data)
        return instance


class getUserRequestSerializer(serializers.ModelSerializer):
    user_field_name = None

    class getUserRequestSerializerException(Exception):
        ...

    def validate(self, attrs):
        if self.user_field_name is None:
            raise ValueError("getUserRequestSerializer需要定义user_field_name来制定user的字段")
        active = self.context.get('request', None)
        if active is None:
            raise self.getUserRequestSerializerException("视图函数需要实现withUserModelSetView接口")

        user = self.context.get('user')
        attrs[self.user_field_name] = user
        # 返回校验后的数据字典
        return attrs
